import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';

@Injectable()
export class UrlInterceptor implements HttpInterceptor {
  prefix = 'api';

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    let _prefix = req.params.get('$prefix');

    // 特殊处理CHANGELOG的加载
    if (req.url !== 'assets/live/CHANGELOG.md') {
      this.prefix = '';
    }

    // 删除$prefix参数
    req = req.clone({
      params: req.params.delete('$prefix')
    });

    if (_prefix !== 'none') {
      _prefix = _prefix || this.prefix;

      req = req.clone({
        url: _prefix + (req.url.startsWith('/') ? '' : '/') + req.url
      });
    }

    return next.handle(req);
  }
}
